﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BulldogCMS.Core.Storage;
using BulldogCMS.Core.Runtime.Modules;

namespace BulldogCMS.Core.MVC
{
    public class URLResolver : IURLResolver
    {
        public Node GetNodeByURL(HttpRequest request, out Site currentSite)
        {
            currentSite = this.GetSiteFromRequest(request);
            if (currentSite != null)
            {
                if (currentSite.RootNode == null)
                {
                    currentSite.RootNode = Context.Application.Tree.GetNode(currentSite.ContentPath);
                }
            } else {
                throw new ApplicationException("Resource not found. 404 probably");
            }

            string siteRootNodeRelativePath = this.GetSiteRootNodeRelativePath(currentSite.RootNode, request);

            Node requestedNode = Context.Application.Tree.GetNode(currentSite.RootNode, siteRootNodeRelativePath);
            return requestedNode;
        }

        private string GetSiteRootNodeRelativePath(Node siteRootNode, HttpRequest request)
        {
            string relativePath = request.Path.TrimStart('/');
            return relativePath;
        }

        private Site GetSiteFromRequest(HttpRequest request)
        {
            var site = (from p in Context.Application.Sites
                        where string.Compare(p.HostName, request.Url.Host) == 0 && request.Url.Port == p.Port
                        select p).FirstOrDefault();
            return site;
        }


    }
}